import string
from io import BytesIO
from random import choices

from captcha.image import ImageCaptcha


def gen_captcha(byte_stream: bool = False):
    text = "".join(choices(string.digits + string.ascii_letters, k=4))
    image = ImageCaptcha().generate_image(text)
    if byte_stream:
        byte_io = BytesIO()
        image.save(byte_io, "JPEG")
        byte_io.seek(0)
        result = byte_io
    else:
        result = image
    return result, text
